# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''单例模式

说明:
    1. 使用元类来实现
    2. 使用类方法来实现

历史:
    2018-10-25 姚彧 创建
'''

__all__ = ['MetaSingleton', 'Singleton']


class MetaSingleton(type):
    '''单键模式元类

    用法:
        class Klass(object, metaclass=MetaSingleton):
    '''
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Singleton(object):
    '''基于类方法的类全局对象
    可以处理元类冲突问题(metaclass conflict)
    '''
    __instance = None
    @classmethod
    def getInstance(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = cls(*args, **kwargs)
        return cls.__instance
